<?php
namespace App\Api\Controllers\Zgyd;

use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\UserWalletDetail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LogicController extends BaseController
{
    public function __construct()
    {

    }

    public function qrSubmitParams ($data_insert, $data)
    {
        try {
            $config = $this->config($data['config_id']);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大支付配置不存在请检查配置'
                ]);
            }
            $merchant = $this->merchant($data['store_id'], $data['store_pid']);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大支付商户号不存在'
                ]);
            }
            //支付宝
            if ($data['ways_type'] == '130002') {
                $out_trade_no =  date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
                //入库参数
                $data_insert['ways_type'] = $data['ways_type'];
                $data_insert['ways_type_desc'] = '支付宝';
                $data_insert['ways_source'] = 'alipay';
                $data_insert['ways_source_desc'] = '支付宝';
                $data_insert['out_trade_no'] = $out_trade_no;
            }
            //云闪付
            if ($data['ways_type'] == '130003') {
                $out_trade_no =  date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
                //入库参数
                $data_insert['ways_type'] = $data['ways_type'];
                $data_insert['ways_type_desc'] = '银联支付';
                $data_insert['ways_source'] = 'unionpay';
                $data_insert['ways_source_desc'] = '银联支付';
                $data_insert['out_trade_no'] = $out_trade_no;
            }
            //微信
            if ($data['ways_type'] == '130001') {
                $out_trade_no =  date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
                //入库参数
                $data_insert['ways_type'] = $data['ways_type'];
                $data_insert['ways_type_desc'] = '微信支付';
                $data_insert['ways_source'] = 'weixin';
                $data_insert['ways_source_desc'] = '微信支付';
                $data_insert['out_trade_no'] = $out_trade_no;
            }

            $payData = [
                "mch_id" => $merchant->mch_id,
                "pos_no" => $merchant->pos_no,
                "pri_key" => $merchant->pri_key,
                "sales_no" => $merchant->sales_no,
                "out_trade_no" => $out_trade_no,
                "total_amount" => $data['total_amount']
            ];
            $return = (new PayController())->qr_submit($payData);
            if ($return['status'] == 1) {
                $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
                if (!$insert_re) {
                    return json_encode([
                        'status' => 2,
                        'message' => '订单未入库'
                    ]);
                }
                return json_encode([
                    'status' => 1,
                    'data' => $return['data']
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getLine()
            ]);
        }
    }


    public function payParams ($data_insert, $data)
    {
        try {
            $store_id = $data['store_id'] ?? '';
            $store_pid = $data['store_pid'] ?? '';
            $merchant_id = $data['merchant_id'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $ways_type = $data['ways_type'] ?? '';
            $store_name = $data['store_name'] ?? '';
            $config_id = $data['config_id'] ?? '';
            $ways_type_desc = $data['ways_type_desc'] ?? '';
            $ways_source = $data['ways_source'] ?? '';
            $title = $data['title'] ?? '';
            $tg_user_id = $data['tg_user_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $code = $data['code'] ?? '';
            $company = $data['company'] ?? '';
            $ways_source_desc = $data['ways_source_desc'] ?? '';
            $device_id = $data['device_id'] ?? ''; //终端设备号.注:当中国银联时,为必填

            $config = $this->config($data['config_id']);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大配置不存在请检查配置'
                ]);
            }
            $merchant = $this->merchant($data['store_id'], $data['store_pid']);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大商户号不存在'
                ]);
            }

            //入库参数
            $data_insert['out_trade_no'] = $out_trade_no;
            $data_insert['ways_type'] = $ways_type;
            $data_insert['ways_type_desc'] = $ways_type_desc;
            $data_insert['ways_source'] = $ways_source;
            $data_insert['company'] = $company;
            $data_insert['ways_source_desc'] = $ways_source_desc;

            $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
            if (!$insert_re) {
                return json_encode([
                    'status' => 2,
                    'message' => '订单未入库'
                ]);
            }

            $payData = [
                "mch_id" => $merchant->mch_id,
                "pos_no" => $merchant->pos_no,
                "pri_key" => $merchant->pri_key,
                "sales_no" => $merchant->sales_no,
                "out_trade_no" => $out_trade_no,
                "desc" => $title,
                "total_amount" => $total_amount,
                "code" => $code,
                'ways_source' => $ways_source
            ];
            Log::channel("zgyd")->info("scan_Request_goods", $data);
            //单品
            $isGoods = 2;
            if (isset($data['store_id']) && !empty($data['store_id'])) {
                $isGoods =  \App\Models\Store::where('store_id', $data['store_id'])->value('is_goods');
            }
            $couponDetail = '';
            if (isset($data['couponDetail']) && !empty($data['couponDetail'])) {
                $couponDetail = json_decode($data['couponDetail'], true);
                Log::channel("zgyd")->info("scan_Request_goods", $couponDetail);
            }

            $payData['body'] = '支付';
            if (isset($couponDetail['goods_detail']) && !empty($couponDetail['goods_detail']) && $isGoods == 1) {
                $goods_detail= [];
                foreach($couponDetail['goods_detail'] as $k=>$v){
                    $goods_detail[$k]['goodsName'] = $v['goods_name'];
                    $goods_detail[$k]['quantity']  = $v['quantity'];
                    $goods_detail[$k]['price']     = $v['price'] * 0.01;
                    $goods_detail[$k]['goodsId']   = $v['goods_id'];
                }
                $Detail['receiptId']   = $couponDetail['receipt_id'];
                $Detail['goodsDetail'] = $goods_detail;
                $Detail['costPrice']   = $couponDetail['cost_price'] * 0.01;
                $payData['body']       = json_encode($Detail,JSON_UNESCAPED_UNICODE);
            }


            $return = (new PayController())->scan_pay($payData);
            //返回支付成功
            if ($return['status'] == 1) {
                $trade_no = '';
                if ($return['data']['PayType'] == 'ZFBA') {
                    $trade_no = isset($return['data']['TradeNo']) ? $return['data']['TradeNo'] : '';
                }

                if ($return['data']['PayType'] == 'WEIX') {
                    $trade_no = isset($return['data']['TradeId']) ? $return['data']['TradeId'] : '';
                }

                $buyer_user_id = '';

                if (isset($return['data']['BuyerId'])) {
                    $buyer_user_id = $return['data']['BuyerId'];
                }

                $pay_time = $return['data']['BankDate'].$return['data']['BankTime'];
                $buyer_pay_amount = $return['data']['TranAmt'] * 0.01;
                //添加扩展数据
                \App\Models\OrderExtend::create([
                    'out_trade_no' => $out_trade_no,
                    'transactionId' => $trade_no,
                    'user_bar_code' => isset($return['data']['OrderNo']) ? $return['data']['OrderNo'] : '',
                ]);
                $update_data = [
                    'trade_no' => $trade_no,
//                    'other_no' => $other_no,
                    'buyer_id' => $buyer_user_id,
                    'status' => '1',
                    'pay_status_desc' => '支付成功',
                    'pay_status' => 1,
                    'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                    'pay_time' => $pay_time,
                    'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
                ];
                (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $out_trade_no);

                //支付成功后的动作
                $data = [
                    'ways_type' => $data['ways_type'],
                    'ways_type_desc' => $data['ways_type_desc'],
                    'company' => $data_insert['company'],
                    'source_type' => '130001', //返佣来源
                    'source_desc' => '中国亚大', //返佣来源说明
                    'total_amount' => $total_amount,
                    'other_no' => $data_insert['other_no'],
                    'out_trade_no' => $out_trade_no,
                    'rate' => $data_insert['rate'],
                    'fee_amount' => $data_insert['fee_amount'],
                    'merchant_id' => $merchant_id,
                    'store_id' => $store_id,
                    'user_id' => $tg_user_id,
                    'config_id' => $config_id,
                    'store_name' => $store_name,
                    'ways_source' => $data['ways_source'],
                    'pay_time' => $pay_time,
                    'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
                ];
                PaySuccessAction::action($data);

                return json_encode([
                    'status' => 1,
                    'pay_status' => '1',
                    'message' => '支付成功',
                    'data' => [
                        'out_trade_no' => $out_trade_no,
                        'ways_type' => $ways_type,
                        'total_amount' => $total_amount,
                        'store_id' => $store_id,
                        'store_name' => $store_name,
                        'config_id' => $config_id,
                        'pay_time' => $pay_time,
                        'trade_no' => $trade_no,
                        'ways_source' => $data['ways_source'],
                    ]
                ]);
            } elseif ($return['status'] == 2) {
                return json_encode([
                    'status' => 1,
                    'pay_status' => 2,
                    'message' => '支付中',
                    'data' => [
                        'out_trade_no' => $out_trade_no,
                        'ways_type' => $ways_type,
                        'ways_source' => $data['ways_source'],
                        'total_amount' => $total_amount,
                        'store_id' => $store_id,
                        'store_name' => $store_name,
                        'config_id' => $config_id,
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getLine()
            ]);
        }
    }

    public function queryParams ($store_id, $store_pid, $data, $order)
    {
        try {
            $config = $this->config($order->config_id);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大支付配置不存在请检查配置'
                ]);
            }

            $merchant = $this->merchant($store_id, $store_pid);

            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大支付商户号不存在'
                ]);
            }


            $payData = [
                "mch_id" => $merchant->mch_id,
                "pos_no" => $merchant->pos_no,
                "pri_key" => $merchant->pri_key,
                "sales_no" => $merchant->sales_no,
                'ways_source' => $order->ways_source,
                'total_amount' => $order->total_amount,
                "out_trade_no" => $order->out_trade_no
            ];
            $return = (new PayController())->order_query($payData);

            //返回支付成功
            if ($return['status'] == 1) {
                $trade_no = '';
                if ($return['data']['OldPayType'] == 'ZFBA') {
                    $trade_no = isset($return['data']['OldTradeNo']) ? $return['data']['OldTradeNo'] : '';
                }

                if ($return['data']['OldPayType'] == 'WEIX') {
                    $trade_no = isset($return['data']['OldTradeId']) ? $return['data']['OldTradeId'] : '';
                }

                $buyer_user_id = '';

                if (isset($return['data']['BuyerId'])) {
                    $buyer_user_id = $return['data']['BuyerId'];
                }

                $pay_time = $return['data']['BankDate'].$return['data']['BankTime'];
                $buyer_pay_amount = $return['data']['OldTranAmt'] * 0.01;

                //添加扩展数据
                \App\Models\OrderExtend::create([
                    'out_trade_no' => $order->out_trade_no,
                    'transactionId' => $trade_no,
                    'user_bar_code' => isset($return['data']['OldOrderNo']) ? $return['data']['OldOrderNo'] : '',
                ]);

                if ($order->pay_status != 1) {
                    $update_data = [
                        'trade_no' => $trade_no,
    //                'other_no' => $other_no,
                        'buyer_id' => $buyer_user_id,
                        'status' => '1',
                        'pay_status_desc' => '支付成功',
                        'pay_status' => 1,
                        'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                        'pay_time' => $pay_time,
                        'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
                    ];
                    (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $order->out_trade_no);
    
                    //支付成功后的动作
                    $data = [
                        'ways_type' => $order->ways_type,
                        'ways_type_desc' => $order->ways_type_desc,
                        'company' => $order->company,
                        'source_type' => '130001', //返佣来源
                        'source_desc' => '中国亚大', //返佣来源说明
                        'total_amount' => $order->total_amount,
                        'other_no' => $order->other_no,
                        'out_trade_no' => $order->out_trade_no,
                        'rate' => $order->rate,
                        'fee_amount' => $order->fee_amount,
                        'merchant_id' => $order->merchant_id,
                        'store_id' => $store_id,
                        'user_id' =>  $order->user_id,
                        'config_id' => $order->config_id,
                        'store_name' =>  $order->store_name,
                        'ways_source' =>  $order->ways_source,
                        'pay_time' => $pay_time,
                        'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
                    ];
                    PaySuccessAction::action($data);
                }
                return json_encode([
                    'status' => 1,
                    'pay_status' => '1',
                    'message' => '支付成功',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        'config_id' => $order->config_id,
                        'pay_time' => $pay_time,
                        'trade_no' => $trade_no,
                        'ways_source' => $order->ways_source,
                    ]
                ]);
            } //支付中
            elseif ($return['status'] == 2) {
                return json_encode([
                    'status' => 1,
                    'pay_status' => 2,
                    'message' => '支付中',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'ways_source' => $order->ways_source,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        'config_id' => $order->config_id
                    ]
                ]);
            }
            else {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }
         } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getLine()
            ]);
        }
    }

    public function refundParams($data, $order)
    {
        try {
            $config = $this->config($order->config_id);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大支付配置不存在请检查配置'
                ]);
            }
            $merchant = $this->merchant($data['store_id'], $data['store_pid']);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '中国亚大支付商户号不存在'
                ]);
            }
            $count = RefundOrder::where(['out_trade_no' => $data['out_trade_no']])->count();

            $user_bar_code = \App\Models\OrderExtend::where(['out_trade_no' => $order->out_trade_no])->where(['transactionId' => $order->trade_no])->value('user_bar_code');

            $payData = [
                "mch_id" => $merchant->mch_id,
                "pos_no" => $merchant->pos_no,
                "pri_key" => $merchant->pri_key,
                "sales_no" => $merchant->sales_no,
                "out_trade_no" => $order->out_trade_no,
                "refund_amount" => $data['refund_amount'],
                "refund_no" => $data['refund_no'].$count,

                'ways_source' => $order->ways_source,
                'total_amount' => $order->total_amount,
                'pay_time' => $order->pay_time,
                'user_bar_code' => $user_bar_code

            ];


            $return = (new PayController())->refund($payData);

            //退款请求成功
            if ($return['status'] == '1') {
                $insert_data = [
                    'status' => '6',
                    'pay_status' => 6,
                    'pay_status_desc' => '已退款',
                    'refund_amount' => $data['new_refund_amount'],
                    'fee_amount' => $data['new_fee_amount']
                ];
                (new \App\Api\Controllers\BaseController())->update_day_order($insert_data, $data['out_trade_no']);

                RefundOrder::create([
                    'ways_source' => $order->ways_source,
                    'type' => $data['ways_type'],
                    'refund_amount' => $data['refund_amount'], //退款金额
                    'refund_no' => $payData['refund_no'], //平台退款单号
                    'store_id' => $data['store_id'],
                    'merchant_id' => $data['merchant_id'],
                    'out_trade_no' => $data['out_trade_no'],
                    'trade_no' => $order->trade_no
                ]);
                //退款成功后的操作
                RefundSuccessAction::action([
                    'out_trade_no'=>$data['out_trade_no'],
                    'refund_no' => $payData['refund_no'], //平台退款单号
                ]);

                //返佣去掉
                UserWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                    'settlement' => '03',
                    'settlement_desc' => '退款订单'
                ]);
                MerchantWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                    'settlement' => '03',
                    'settlement_desc' => '退款订单'
                ]);

                $data = [
                    'refund_amount' => $data['refund_amount'],
                    'out_trade_no' => $data['out_trade_no'],
                    'refund_no' => $payData['refund_no'], //平台退款单号
                    'other_no' => $order->trade_no
                ];
                return json_encode([
                    'status' => '1',
                    'message' => '退款成功',
                    'data' => $data
                ]);
            } //退款处理中
            elseif($return['status'] == '3') {
                $insert_data = [
                    'status' => '5',
                    'pay_status' => 5,
                    'pay_status_desc' => '退款中'
                ];
                $res = $this->update_day_order($insert_data, $data['out_trade_no']);
                if (!$res) {
                    Log::info('中国亚大-退款中-更新失败');
                }

                $refund_count = $return['data']['refund_count']-1; //退款记录数
                $data = [
                    'refund_amount' => $data['refund_amount'],
                    'out_trade_no' => $data['out_trade_no'],
                    'refund_no' => $return['data']['refund_id_'.$refund_count], //平台退款单号
                    'other_no' => $data['other_no']
                ];
                return json_encode([
                    'status' => '1',
                    'message' => '退款中',
                    'data' => $data
                ]);
            }
            else {

                //其他情况
                $message = $return['message'];
                return json_encode([
                    'status' => '2',
                    'message' => $message
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getLine()
            ]);
        }
    }


    public function config($config_id)
    {
        //配置取缓存
        $config = DB::table("zgyd_configs")->where('config_id', $config_id)
            ->first();
        if (!$config) {
            $config = DB::table("zgyd_configs")->where('config_id', '1234')->first();
        }

        return $config;
    }


    public function merchant($store_id, $store_pid)
    {
        if ($store_pid) {
            //分店配置
            $payStore = DB::table("zgyd_stores")->where('store_id', $store_id)->first();
            if (!$payStore) {
                $store_pid_id = '';
                $store_p = Store::where('id', $store_pid)
                    ->select('store_id')
                    ->first();
                if ($store_p) {
                    $store_pid_id = $store_p->store_id;
                }
                $payStore = DB::table("zgyd_stores")->where('store_id', $store_pid_id)->first();
            }
        } else {
            $payStore = DB::table("zgyd_stores")->where('store_id', $store_id)->first();
        }
        return $payStore;
    }

    public function terminal ($store_id)
    {

    }





}
